<!DOCTYPE html>


<html lang="zh-CN">


<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    Python 中操作常见的配置文件.md |  
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-develop/Python 中操作常见的配置文件"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  Python 中操作常见的配置文件.md
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2020/11/11/develop/Python%20%E4%B8%AD%E6%93%8D%E4%BD%9C%E5%B8%B8%E8%A7%81%E7%9A%84%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6/" class="article-date">
  <time datetime="2020-11-10T16:00:00.000Z" itemprop="datePublished">2020-11-11</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/develop/">develop</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">2.8k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">11 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <h1 id="Python-中操作常见的配置文件"><a href="#Python-中操作常见的配置文件" class="headerlink" title="Python 中操作常见的配置文件"></a>Python 中操作常见的配置文件</h1><h3 id="为什么要写配置文件"><a href="#为什么要写配置文件" class="headerlink" title="为什么要写配置文件"></a>为什么要写配置文件</h3><p>在开发过程中，我们常常会用到一些固定参数或者是常量。对于这些较为固定且常用到的部分，往往会将其写到一个固定文件中，避免在不同的模块代码中重复出现从而保持核心代码整洁。这个固定文件我们可以直接写成一个 <code>.py</code> 文件，例如 <code>settings.py</code> 或 <code>config.py</code>，这样的好处就是能够在同一工程下直接通过 <code>import</code> 来导入当中的部分；但如果我们需要在其他<strong>非 Python 的平台</strong>进行配置文件共享时，写成单个 <code>.py</code> 就不是一个很好的选择。这时我们就应该选择通用的配置文件类型来作为存储这些固定的部分。目前常用且流行的配置文件格式类型主要有 <code>ini</code>、<code>json</code>、<code>toml</code>、<code>yaml</code>、<code>xml</code> 等，这些类型的配置文件我们都可以通过标准库或第三方库来进行解析。</p>
<h3 id="ini"><a href="#ini" class="headerlink" title="ini"></a>ini</h3><p><code>ini</code> 即 Initialize 初始化之意，早期是在 Windows 上配置文件的存储格式。<code>ini</code> 文件的写法通俗易懂，往往比较简单，通常由节（Section）、键（key）和值（value）组成，就像以下形式：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line">\[localdb\]    </span><br><span class="line">host     &#x3D; 127.0.0.1    </span><br><span class="line">user     &#x3D; root    </span><br><span class="line">password &#x3D; 123456    </span><br><span class="line">port     &#x3D; 3306    </span><br><span class="line">database &#x3D; mysql    </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>Python 本身内置的 <code>configparser</code> 标准库，我们直接就可以用来对 <code>ini</code> 文件进行解析。如我们将上述内容保存在一个名为 <code>db.ini</code> 的文件中，然后使用 <code>read()</code> 方法来进行解析和读取，最后通过 <code>items()</code> 方法来获取指定节点下的所有键值对。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line">\&gt;&gt;&gt; from configparser import ConfigParser    </span><br><span class="line">\&gt;&gt;&gt; cfg &#x3D; ConfigParser()    </span><br><span class="line">\&gt;&gt;&gt; cfg.read(&quot;&#x2F;Users&#x2F;Bobot&#x2F;db.ini&quot;)    </span><br><span class="line">\[&#39;&#x2F;Users&#x2F;Bobot&#x2F;db.ini&#39;\]    </span><br><span class="line">\&gt;&gt;&gt; cfg.items(&quot;localdb&quot;)    </span><br><span class="line">\[(&#39;host&#39;, &#39;127.0.0.1&#39;), (&#39;user&#39;, &#39;root&#39;), (&#39;password&#39;, &#39;123456&#39;), (&#39;port&#39;, &#39;3306&#39;), (&#39;database&#39;, &#39;mysql&#39;)\]    </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>需要注意的是，<code>configparser</code> 默认将值<strong>以字符串的形式</strong>呈现，所以这也就是为什么我们在 <code>db.ini</code> 文件中没有加引号而是直接将字面量写在上面的原因。获取到键值对后，我其实直接就将其转换成字典，然后通过解包的方式进行穿参，保持代码简洁：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line">#!pip install pymysql    </span><br><span class="line">import pymysql    </span><br><span class="line">from configparser import ConfigParser    </span><br><span class="line">    </span><br><span class="line">cfg &#x3D; ConfigParser()    </span><br><span class="line">cfg.read(&quot;&#x2F;Users&#x2F;Bobot&#x2F;db.ini&quot;)    </span><br><span class="line">db\_cfg &#x3D; dict(cfg.items(&quot;localdb&quot;))    </span><br><span class="line">    </span><br><span class="line">con &#x3D; pymysql.connect(\*\*db\_cfg)    </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="json"><a href="#json" class="headerlink" title="json"></a>json</h3><p><code>json</code> 格式可以说是我们常见的一种文件形式了，也是目前在互联网较为流行的一种数据交换格式。除此之外，<code>json</code> 有时也是配置文件的一种。比如 <code>npm</code>（JavaScript 包管理工具类似 Python 的 <code>pip</code>）、以及微软出品的目前被广泛使用的 VSCode 编辑器，都使用 <code>json</code> 编写配置参数。和 <code>configparser</code> 一样，Python 也内置了 <code>json</code> 标准库，可以通过 <code>load()</code> 和 <code>loads()</code> 方法来导入文件式和字符串的 <code>json</code> 内容。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line">&#123;    </span><br><span class="line">    &quot;localdb&quot;:&#123;    </span><br><span class="line">        &quot;host&quot;: &quot;127.0.0.1&quot;,    </span><br><span class="line">        &quot;user&quot;: &quot;root&quot;,    </span><br><span class="line">        &quot;password&quot;: &quot;123456&quot;,    </span><br><span class="line">        &quot;port&quot;: 3306,    </span><br><span class="line">        &quot;database&quot;: &quot;mysql&quot;    </span><br><span class="line">    &#125;    </span><br><span class="line">&#125;      </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>我们将上述内容保存为 <code>db.json</code> 后进行读取和解析，<code>json</code> 库读取 json 文件相对简单容易，而且很容易解析成 Python 的字典对象。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line">\&gt;&gt;&gt; import json    </span><br><span class="line">\&gt;&gt;&gt; from pprint import pprint    </span><br><span class="line">\&gt;&gt;&gt;     </span><br><span class="line">\&gt;&gt;&gt; with open(&#39;&#x2F;Users&#x2F;Bobot&#x2F;db.json&#39;) as j:    </span><br><span class="line">...     cfg &#x3D; json.load(j)\[&#39;localdb&#39;\]    </span><br><span class="line">...     </span><br><span class="line">\&gt;&gt;&gt; pprint(cfg)    </span><br><span class="line">&#123;&#39;database&#39;: &#39;mysql&#39;,    </span><br><span class="line"> &#39;host&#39;: &#39;127.0.0.1&#39;,    </span><br><span class="line"> &#39;password&#39;: &#39;123456&#39;,    </span><br><span class="line"> &#39;port&#39;: 3306,    </span><br><span class="line"> &#39;user&#39;: &#39;root&#39;&#125;    </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>使用 <code>json</code> 文件配置的缺点就是语法标准严格限制，为人所诟病之一的就是<strong>无法在当中写注释</strong>，除非采取 <code>json</code> 类型的其他<strong>超集</strong>作为替代方案（VSCode 中能写注释的 <code>json</code> 参数配置文件便是代替方案的一种）；同时存在<strong>嵌套过深</strong>的问题，容易导致出错，不宜用来写过长或复杂的参数配置信息。</p>
<h3 id="toml"><a href="#toml" class="headerlink" title="toml"></a>toml</h3><p><code>toml</code> 格式（或 <code>tml</code> 格式）是 Github 联合创始人 Tom Preston-Werner 所提出的一种配置文件格式。根据维基百科的资料，<code>toml</code> 最开始提出时是在 2013年7月份，距今已有七年时间；它在某些方面也与后面要谈到的 <code>yaml</code> 文件有些类似，但如果当你知道 yaml 的规范有几十页（没有错，真的就是几十页……）的时候，可能你真的就不太愿意去写那么复杂的配置文件，<code>toml</code> 格式则倒是个不错的选择。<code>toml</code> 格式大致如下：</p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/5mt0ewv9OS3n49UQqicXusCZzrNGgd6MJPcLM1yTZsL16mQBWEebp52usyuMjZH00mx5uJVEwsiaOsvgVmLXGjnw/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1"></p>
<p>从这里可以看出 <code>toml</code> 有点类似于前面所讲的 <code>ini</code> 文件。但是它比 <code>ini</code> 扩展了更多的内容。在样例图片中我们可以看到，除了基本的字符串以外，例如时间戳、布尔值、数组等都进一步支持，而且样式和 Python 的原生写法十分类似。当然这里不会过多介绍 <code>toml</code> 格式的一些规范说明，有人已经对官方的规范文档进行了翻译，有兴趣的朋友可以直接查阅。这么契合 Python 方式的配置文件类型已经有开发者造出了相应的「轮子」，目前在 Github 上 Stars 数最多的是则 <code>uiri/toml</code> 的版本，不过该版本仅通过了 v0.5 版本 <code>toml</code> 规范，但在使用上还是蛮简洁的，我们可以通过 <code>pip</code> 命令进行安装</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line">pip install toml    </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>该库的解析方式很简单，也有点类似于 <code>json</code> 库的解析用法，即通过<code>load()</code> 或 <code>loads()</code> 来进行解析；同理转换并导出也是同样类似的用法。比如我们现在将以下内容写入到 <code>config.toml</code> 中：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line">\[mysql\]    </span><br><span class="line">host     &#x3D; &quot;127.0.0.1&quot;    </span><br><span class="line">user     &#x3D; &quot;root&quot;    </span><br><span class="line">port     &#x3D; 3306    </span><br><span class="line">database &#x3D; &quot;test&quot;    </span><br><span class="line">    </span><br><span class="line">  \[mysql.parameters\]    </span><br><span class="line">  pool\_size &#x3D; 5    </span><br><span class="line">  charset   &#x3D; &quot;utf8&quot;    </span><br><span class="line">    </span><br><span class="line">  \[mysql.fields\]    </span><br><span class="line">  pandas\_cols &#x3D; \[ &quot;id&quot;, &quot;name&quot;, &quot;age&quot;, &quot;date&quot;\]    </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>紧接着我们就可以通过 <code>toml</code> 库中的 <code>load()</code> 方法来进行读取：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line">\&gt;&gt;&gt; import toml    </span><br><span class="line">\&gt;&gt;&gt; import os    </span><br><span class="line">\&gt;&gt;&gt; from pprint import pprint    </span><br><span class="line">\&gt;&gt;&gt; cfg &#x3D; toml.load(os.path.expanduser(&quot;~&#x2F;Desktop&#x2F;config.toml&quot;))    </span><br><span class="line">\&gt;&gt;&gt; pprint(cfg)    </span><br><span class="line">&#123;&#39;mysql&#39;: &#123;&#39;database&#39;: &#39;test&#39;,    </span><br><span class="line">           &#39;fields&#39;: &#123;&#39;pandas\_cols&#39;: \[&#39;id&#39;, &#39;name&#39;, &#39;age&#39;, &#39;date&#39;\]&#125;,    </span><br><span class="line">           &#39;host&#39;: &#39;127.0.0.1&#39;,    </span><br><span class="line">           &#39;parameters&#39;: &#123;&#39;charset&#39;: &#39;utf8&#39;, &#39;pool\_size&#39;: 5&#125;,    </span><br><span class="line">           &#39;port&#39;: 3306,    </span><br><span class="line">           &#39;user&#39;: &#39;root&#39;&#125;&#125;    </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>可以看到 <code>toml</code> 文件被间接地转化成了字典类型，当然这也就是 <code>json</code> 版的写法（将单引号替换成双引号即可），方便我们后续调用或者传参。</p>
<h3 id="yaml"><a href="#yaml" class="headerlink" title="yaml"></a>yaml</h3><p><code>yaml</code> 格式（或 <code>yml</code> 格式）是目前较为流行的一种配置文件，它早在 2001 由一个名为 Clark Evans 的人提出；同时它也是目前被广泛使用的配置文件类型，典型的就是 Docker 容器里的 <code>docker-compose.yml</code> 配置文件，如果经常使用 Docker 进行部署的人对此不会陌生。<code>yaml</code> 文件的设计从 Python、XML 等地方获取灵感，所以在使用时能很清楚地看到这些部分的影子。在上一节 <code>toml</code> 内容里我曾提到，<code>yaml</code> 的规范内容可以说是冗长和复杂，足足有80页之多（斗尊强者，恐怖如斯……）。</p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/5mt0ewv9OS3n49UQqicXusCZzrNGgd6MJIqUFBT08EqLEhgicHuib4cyVyhTPPicWbLZRwnia0sOgQP4r7Y0SuK36lg/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1">02-yaml规范页数</p>
<p>所以感兴趣的朋友可以再自行了解相关用法。YAML 官方早已经提供了相应的 Python 库进行支持，即 <code>PyYAML</code>；当然也同样需要我们事先进行安装：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line">pip install pyyaml    </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>同 <code>json</code> 库和 <code>toml</code> 库一样，通过 <code>load()</code> 方法来进行加载。需要注意的是，使用 <code>load()</code> 方法<strong>会存在一定的安全隐患</strong>，从思科 Talos 的这份报告中我们可以看到，如果加载了未知或不信任的 <code>yaml</code> 文件，那么有可能会存在被攻击的风险和网络安全隐患，因为它能够直接调用相应的 Python 函数来执行为攻击者所需要的命令，比如说在 <code>yaml</code> 文件中写入这么一段：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line"># 使用Linux和macOS的朋友不要轻易尝试    </span><br><span class="line">!!python&#x2F;object&#x2F;apply:os.system \[&quot;rm -rf &#x2F;&quot;\]    </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>因此最好是使用 <code>safe_load()</code> 来代替 <code>load()</code> 方法。这和 Python 内置的 <code>string</code> 标准库中 <code>Template</code> 类的 <code>substitute()</code> 模板方法一样存在着同样的安全隐患，所以使用 <code>safe_substitute()</code> 来替代是一样的道理。如我们现在将之前的一些配置信息写入 <code>config.yaml</code> 文件中：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line">mysql:    </span><br><span class="line">  host: &quot;127.0.0.1&quot;    </span><br><span class="line">  port: 3306    </span><br><span class="line">  user: &quot;root&quot;    </span><br><span class="line">  password: &quot;123456&quot;    </span><br><span class="line">  database: &quot;test&quot;    </span><br><span class="line">    </span><br><span class="line">  parameter:    </span><br><span class="line">    pool\_size: 5    </span><br><span class="line">    charset: &quot;utf8&quot;    </span><br><span class="line">    </span><br><span class="line">  fields:    </span><br><span class="line">    pandas\_cols:     </span><br><span class="line">      - id    </span><br><span class="line">      - name    </span><br><span class="line">      - age    </span><br><span class="line">      - date    </span><br><span class="line">    </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>然后我们通过 <code>safe_load()</code> 方法进行解析：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line">\&gt;&gt;&gt; import os    </span><br><span class="line">\&gt;&gt;&gt; from pprint import pprint    </span><br><span class="line">\&gt;&gt;&gt;     </span><br><span class="line">\&gt;&gt;&gt; with open(os.path.expanduser(&quot;~&#x2F;config.yaml&quot;), &quot;r&quot;) as config:    </span><br><span class="line">...     cfg &#x3D; yaml.safe\_load(config)    </span><br><span class="line">...     </span><br><span class="line">\&gt;&gt;&gt; pprint(cfg)    </span><br><span class="line">&#123;&#39;mysql&#39;: &#123;&#39;database&#39;: &#39;test&#39;,    </span><br><span class="line">           &#39;fields&#39;: &#123;&#39;pandas\_cols&#39;: \[&#39;id&#39;, &#39;name&#39;, &#39;age&#39;, &#39;date&#39;\]&#125;,    </span><br><span class="line">           &#39;host&#39;: &#39;127.0.0.1&#39;,    </span><br><span class="line">           &#39;parameter&#39;: &#123;&#39;charset&#39;: &#39;utf8&#39;, &#39;pool\_size&#39;: 5&#125;,    </span><br><span class="line">           &#39;password&#39;: &#39;123456&#39;,    </span><br><span class="line">           &#39;port&#39;: 3306,    </span><br><span class="line">           &#39;user&#39;: &#39;root&#39;&#125;&#125;    </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>可以看到最后结果和前面的 <code>toml</code> 库的解析结果基本一致。</p>
<h3 id="结尾"><a href="#结尾" class="headerlink" title="结尾"></a>结尾</h3><p>本文列举了一些主流且常见的配置文件类型及其 Python 的读取方法，可能有的读者会发现当中没有 <code>xml</code> 格式类型的内容。对于 <code>xml</code> 配置文件可能与 Java 系语言打交道的朋友遇见得会多一些，但 <code>xml</code> 文件的可读性实在是让人望而生畏；对 <code>xml</code> 文件不了解的朋友可以使用 Chrome 浏览器随便进入一个网站然后按下 F12 进入开发者后查看那密密麻麻的 html 元素便是 <code>.xml</code> 的缩影。除了这些主流的配置文件类型之外，像一些 <code>.cfg</code>、<code>.properties</code> 等都可以作为配置文件，甚至和开头提到的那样，你单独用一个 <code>.py</code> 文件来书写各类配置信息作为配置文件进行导入都是没问题，只是在跨语言共享时可能会有些障碍。因此本文就不过多介绍，感兴趣的朋友可以进一步自行了解。在本文里列举的配置文件类型其复杂性由上到下依次增加：<code>ini &lt; json ≈ toml &lt; yaml</code>，它们之间各有优劣，可以根据自己实际的需求和团队协作要求来具体选择。</p>
<p><em>文章来自：Python中文社区</em>  </p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/QFzRdz9libEagf3GqMkG2r8nyTK3msmDpqnUPzT4HyN6wSpwNia24JAcHeF4BmWKotAqs0IibPkl9CZL3Yp05TCyA/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1"></p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/QFzRdz9libEagf3GqMkG2r8nyTK3msmDpd79yRpcwBjt8yQlG1dJ3NNxtSSqicpdEVFk3iax1ia4p4CoENnkTZh7ibA/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1"></p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/QFzRdz9libEagf3GqMkG2r8nyTK3msmDpIfuyiaAHcXRtjicE7OjbHoHoNMtwgkh6iaAsdFVmrUJ5IEw6zk33KObGg/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1"></p>
<p><strong>马哥教育Linux、Python、Go系列课程火热报名中</strong></p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/2rMyvdWluHs3Xwo84icpXFn5eVv5jBhILen6C64qU5QpmBcALIbBQb53fRvCXicxrqBqJd7dbQG2hhdkvnGUFNQw/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1"></p>
<p>我就知道你“在看”</p>
<p><img src=""></p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2020/11/11/develop/Python%20%E4%B8%AD%E6%93%8D%E4%BD%9C%E5%B8%B8%E8%A7%81%E7%9A%84%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/develop/" rel="tag">develop</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/11/11/develop/PyCharm%20%E4%B8%AD%E6%96%87%E6%8C%87%E5%8D%97/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            PyCharm 中文指南.md
          
        </div>
      </a>
    
    
      <a href="/2020/11/11/develop/Python%20%E7%82%AB%E6%8A%80%E6%93%8D%E4%BD%9C%EF%BC%9A%E6%A8%A1%E5%9D%97%E9%87%8D%E8%BD%BD%E7%9A%84%E4%BA%94%E7%A7%8D%E6%96%B9%E6%B3%95/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">Python 炫技操作：模块重载的五种方法.md</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2020
        <i class="ri-heart-fill heart_icon"></i> TzWind
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        由 <a href="https://hexo.io" target="_blank">Hexo</a> 强力驱动
        <span class="division">|</span>
        主题 - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="Hexo"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" target="_blank" rel="noopener" href="http://www.baidu.com">百度</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/2019/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>